package com.vnp.vchat.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.telpoo.frame.utils.Mlog;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.adapter.TinnhanAdapter;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.util.Common;
import com.vnp.vchat.util.PreferenceHelper;
import com.vnp.vchat.util.Utils;
import com.vnp.vchat.version2.ChatNewActivity;

public class TinNhanScr extends Fragment implements OnTouchListener {

	TextView title;
	ImageButton btnSettings;
	// ArrayList<ObjKhachhang> objKhachhangs = new ArrayList<ObjKhachhang>();
	TinnhanAdapter adapter;
	ListView listTinnhan;
	PreferenceHelper preferenceHelper;

	Handler mHandler = new Handler();

	Runnable r = new Runnable() {

		@Override
		public void run() {
			getDanhsach(mPage);
		}
	};

	Runnable autogetHisMessage = new Runnable() {

		@Override
		public void run() {
			if(!((MainPanelActivity)getActivity()).isSocketConnected())
			getDanhsach(1);
			mHandler.removeCallbacks(autogetHisMessage);
			mHandler.postDelayed(autogetHisMessage, 5000);

		}
	};

	ProgressBar progressBar;

	LinearLayout llNomsg;
	TextView txtNoMsg;
	Button btnSoantin;

	// load more hischat
	private int preLast;
	boolean isLoading = false;
	boolean isCanloadMore = false;
	int mPage = 1;

	MySQLiteHelper db;
	private BroadcastReceiver mReceiver;
	ViewGroup actionbar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		db = new MySQLiteHelper(getActivity());
		preferenceHelper = new PreferenceHelper(getActivity());

	}

	ViewGroup viewGroup;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (viewGroup == null) {
			viewGroup = (ViewGroup) inflater.inflate(R.layout.scr_tin_nhan, container, false);
		} else {
			((ViewGroup) viewGroup.getParent()).removeView(viewGroup);
		}
		actionbar = (ViewGroup) viewGroup.findViewById(R.id.actionbar);
		title = (TextView) viewGroup.findViewById(R.id.title);
		title.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);
		btnSettings = (ImageButton) viewGroup.findViewById(R.id.btn_settings);
		progressBar = (ProgressBar) viewGroup.findViewById(R.id.progress_bar);

		llNomsg = (LinearLayout) viewGroup.findViewById(R.id.ll_nomsg);
		txtNoMsg = (TextView) viewGroup.findViewById(R.id.txt_nomsg);
		btnSoantin = (Button) viewGroup.findViewById(R.id.btn_soantin);

		btnSettings.setVisibility(View.GONE);
		progressBar.setVisibility(View.VISIBLE);

		mHandler.removeCallbacks(r);
		mHandler.postDelayed(r, 300);
		listTinnhan = (ListView) viewGroup.findViewById(R.id.list_tinnhan);
		adapter = new TinnhanAdapter(getActivity(), new ArrayList<ObjKhachhang>());
		listTinnhan.setAdapter(adapter);

		// setDataDemo();

		// objKhachhangs.addAll(db.getAllHisChat());
		//
		// Log.i("vChat", "List hischat to DB: "+objKhachhangs.size());

		setData();
		setFont();

		listTinnhan.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
				MainPanelActivity.onGoto = true;
				Intent c = new Intent(getActivity(), ChatNewActivity.class);
				c.putExtra("khachhang", (ObjKhachhang) arg0.getAdapter().getItem(position));
				startActivity(c);
				getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.over_main_left);
			}
		});

		listTinnhan.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				int lastItem = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount) {
					if (preLast != lastItem) {
						int last_pos = listTinnhan.getLastVisiblePosition();
						if (last_pos >= totalItemCount - 1 && !isLoading && isCanloadMore) {
							btnSettings.setVisibility(View.GONE);
							progressBar.setVisibility(View.VISIBLE);
							getDanhsach(++mPage);
						}
						preLast = lastItem;
					}

				}
			}
		});
		reciveBroadCast();
		init();
		return viewGroup;
	}

	public void count() {
		int count_tn = 0;
		ArrayList<ObjKhachhang> objKH = new ArrayList<ObjKhachhang>();
		for (int i = 0; i < adapter.getCount(); i++) {
			ObjKhachhang objkh = adapter.getItem(i);
			if (objkh.getIsRead() == 1) {
				objKH.add(objkh);
			}
		}
		count_tn = objKH.size();
		((MainPanelActivity) getActivity()).updateMessager(count_tn);
	}

	private void init() {
		btnSettings.setOnTouchListener(this);
		actionbar.setOnTouchListener(this);
		title.setOnTouchListener(this);
	};

	private void setFont() {

		// title.setTypeface(Utils.getTypefaceBlack(TinNhanActivity.this),
		// Typeface.BOLD);
		txtNoMsg.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);
		btnSoantin.setTypeface(Utils.getTypefaceRegular(getActivity()), Typeface.BOLD);
	}

	private void setData() {
		title.setText(R.string.tinnhan);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_settings:
			if (event.getAction() == MotionEvent.ACTION_UP) {

			}
			break;
		case R.id.actionbar:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				scrollToTop();
			}

		case R.id.title:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				Log.i("vChat", "Click vào title------------");
				scrollToTop();
			}
		default:
			break;
		}
		return false;
	}

	void scrollToTop() {
		listTinnhan.smoothScrollToPosition(0);
	}

	public void getDanhsach(int page) {
		Mlog.D("get history list message");
		isLoading = true;
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler() {

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				btnSettings.setVisibility(View.GONE);
				progressBar.setVisibility(View.GONE);
				isLoading = false;
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					btnSettings.setVisibility(View.GONE);
					progressBar.setVisibility(View.GONE);
					isLoading = false;
					int status = re.getInt("status");
					if (status == 1) {
						
						JSONArray his = re.getJSONArray("history");

						Log.i("vChat", "His: " + his);
						// db.deleteHisChat();
						for (int i = 0; i < his.length(); i++) {

							JSONObject hisMsg = his.getJSONObject(i);
							String name;

							if (his.length() < 19) {
								isCanloadMore = false;
							} else {
								isCanloadMore = true;
							}

							if (!hisMsg.getString("use_name").equals("") && !(hisMsg.getString("use_name").equals(null))) {
								name = hisMsg.getString("use_name");
							} else {
								name = hisMsg.getString("use_loginname");
							}

							String urlAvatar = hisMsg.getString("to_image");

							Log.i("vChat", "URL avatar: " + urlAvatar);

							String lastMsg, time;

							if (hisMsg.getJSONArray("last_msg").length() == 0) {
								Log.i("vChat", "Ko co gia tri last message");
								lastMsg = "";
								time = "";
							} else {
								lastMsg = hisMsg.getJSONArray("last_msg").getJSONObject(0).getString("cha_message");
								time = hisMsg.getJSONArray("last_msg").getJSONObject(0).getString("cha_time");
							}

							int online = hisMsg.getInt("online");
							int idKh = hisMsg.getInt("uss_sso_id");
							int isUserVg = hisMsg.getInt("is_uservg");

							String pro_name = null, pro_url = null;

							// check danh sach da xem
							Object obj = hisMsg.get("pro");
							if (obj instanceof JSONObject) {
								JSONObject proObj = (JSONObject) obj;

								pro_name = proObj.getString("pro_name");
								pro_url = proObj.getString("pro_link");

							} else {
								pro_name = "";
								pro_url = "";
								Log.i("vChat", "Ko co ds da xem -----------");
							}

							int statusMsg = db.getStatusMsg(String.valueOf(idKh));

							if (idKh == Integer.valueOf(preferenceHelper.getUserId())) {

							} else {
								ObjKhachhang objKhachhang = new ObjKhachhang();
								objKhachhang.setName(name);
								objKhachhang.setUrlAvatar(urlAvatar);
								objKhachhang.setLastMessage(lastMsg);
								objKhachhang.setTimeLastMessage(time);
								objKhachhang.setOnline(online);
								objKhachhang.setId(String.valueOf(idKh));
								objKhachhang.setIsUserVg(isUserVg);
								objKhachhang.setUrlDangxem(pro_url);
								objKhachhang.setDsDaxem(pro_name);
								objKhachhang.setIsRead(statusMsg);

								//if(!((MainPanelActivity)getActivity()).isSocketConnected())
								db.updateHischat(objKhachhang);
								updateUI();
							}
						}
						getActivity().runOnUiThread(new Runnable() {

							@Override
							public void run() {
								updateUI();
							}
						});
						if (adapter.getCount() > 0) {
							getActivity().runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// adapter.notifyDataSetChanged();
									// listTinnhan.setAdapter(adapter);
									updateUI();
								}
							});

							llNomsg.setVisibility(View.GONE);
							listTinnhan.setVisibility(View.VISIBLE);
						} else {
							llNomsg.setVisibility(View.VISIBLE);
							listTinnhan.setVisibility(View.GONE);

						}

					} else if (status == 0) {

					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
		httpClientHelper.getDanhsachChat(preferenceHelper.getAdminId(), preferenceHelper.getHash(), page, 1);

	}

	void updateUI() {

		ArrayList<ObjKhachhang> ab = db.getAllHisChat();
		//sMlog.T("getDataToDB " + ab.size());
		adapter.setItems(ab);
		count();
		((MainPanelActivity) getActivity()).invalidateViewPager();
	}

	@Override
	public void onResume() {
		super.onResume();
		// KeyboardHelper.hideSoftKeyboard(getActivity());
		updateUI();
		Mlog.T("tinnhanfm onResume");
		count();
		// objKhachhangs.clear();
		mPage = 1;
		mHandler.removeCallbacks(r);
		mHandler.postDelayed(r, 200);
		startGetHistoryAuto();
	}

	private void startGetHistoryAuto() {
		mHandler.removeCallbacks(autogetHisMessage);
		mHandler.postDelayed(autogetHisMessage, 5000);
		
	}

	@Override
	public void onPause() {
		super.onPause();
		mHandler.removeCallbacks(r);
		mHandler.removeCallbacksAndMessages(null);
		mHandler.removeCallbacks(autogetHisMessage);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(r);
		mHandler.removeCallbacksAndMessages(null);
		getActivity().unregisterReceiver(mReceiver);
	}

	private void reciveBroadCast() {
		IntentFilter intentFilter = new IntentFilter();

		intentFilter.addAction(Common.IS_READ);
		intentFilter.addAction(Common.ADD);
		intentFilter.addAction(Common.IS_RELOAD);

		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, final Intent intent) {
				String action = intent.getAction();
				if (action.equals(Common.IS_READ)) {
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// objKhachhangs.clear();
							// objKhachhangs.addAll(db.getAllHisChat());
							// adapter = new TinnhanAdapter(getActivity(),
							// objKhachhangs);
							// adapter.notifyDataSetChanged();
							/*
							 * mHandler.removeCallbacks(r);
							 * mHandler.postDelayed(r, 200);
							 */
							// adapter.notifyDataSetChanged();
							updateUI();
						}
					});
					Log.i("vChat", "Nhan duoc broadcast update trang thai");
				} else if (action.equals(Common.ADD)) {
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// objKhachhangs.clear();
							// objKhachhangs.addAll(db.getAllHisChat());
							// adapter.notifyDataSetChanged();
							updateUI();
							// adapter = new TinnhanAdapter(getActivity(),
							// objKhachhangs);
							// listTinnhan.setAdapter(adapter);
							// count();
						}
					});
				} else if (action.equals(Common.IS_RELOAD)) {
					mHandler.removeCallbacks(r);
					mHandler.postDelayed(r, 300);
				}
			}
		};

		// register
		getActivity().registerReceiver(mReceiver, intentFilter);
	}

}
